#!/bin/bash -e
function usage
    {
        echo -e "usage: git_db_schema [-b branches]\n --h, --help for more detailed instructions"
    }

function help
    {
        echo -e "git_db_schema:"
        echo -e "       -b: list of all branches to apply this schema to, defaults to all"
    }

#Variable defaults
SCHEMADIR='.git_db_schema'
DATABASE=''
BRANCHES=''

#If not in git repo this will fatal fail
GITDIR=$(git rev-parse --show-toplevel)

#get valid branches
VALIDBRANCHES=$(git branch | sed "s/\*//g")


while [ "$1" != "" ] ; do
    case $1 in
        -b )    while [ "$1" != "" ] ; do
                    shift
                    if grep --quiet "$1" <<< $VALIDBRANCHES ;
                    then
                        BRANCHES="$BRANCHES $1"
                    else
                        echo -e "$1 is not a valid branch in your git repository.  Exiting."
                        exit
                    fi
                done
                break
                ;;
        -h )    help
                exit
                ;;
        * )     usage
                exit
    esac
    shift
done


#Check for my.cnf in system
while [[ $CREATEMC != "Y" && $CREATEMC != "N" ]] ; do
    read -p "Would you like to create a db entry in your my.cnf file(Y/N):" CREATEMC
    if [[ $CREATEMC != "Y" && $CREATEMC != "N" ]] ;
    then
        echo -e 'This is not a valid entry'
    fi
done

#Get New DB
while [[ $DATABASE == "" ]] ; do
    read -p "Database name:" DATABASE
    if [ $DATABASE == "" ] ;
    then
        echo -e 'This is not a valid entry'
    fi
done

#Get username and password for mysql
read -p "Mysql username:" MYSQLUSER
read -s -p "Mysql password:" MYSQLPASS
ATTEMPTS=0
echo -e "Testing MYSQL connection"
while ! mysql -u $MYSQLUSER --password="$MYSQLPASS" $DATABASE  -e ";" > /dev/null ; do
    echo -e "Could not connect to MYSQL please try again"
    read -p "Mysql username:" MYSQLUSER
    read -s -p "Mysql password:" MYSQLPASS
    ATTEMPTS=$(expr $ATTEMPTS + 1)
    if [ $ATTEMPTS >= 3 ] ;
    then
        echo -e "Three or more failed attempts, exiting"
        exit
    fi
done


#check ~/.my.cnf for existing configuration
if [ $CREATEMC == "Y" ] ; 
then
    if grep --quiet "client_git_db_schema_$DATABASE" ~/.my.cnf;
    then
        echo -e "There is already an entry for $DATABASE."
        echo -e "Manually edit ~/.my.cnf for client entry client_git_db_schema_$DATABASE if your credentials are incorrect."
    else
        echo -e "Creating db entry in my.cnf"
        MYCNF="\n[client_git_db_schema_$DATABASE]\nuser=$MYSQLUSER\npassword=$MYSQLPASS\nhost=localhost"
        echo -e $MYCNF >> ~/.my.cnf
    fi
fi

#Create schema dir
if [ ! -e $SCHEMADIR ] ;
then
    echo -e "Creating schema directory."
    mkdir $SCHEMADIR
fi

#Write htaccess file
echo -e "Writing htaccess to deny access to schema directory."
echo -e "Insure you have AllowOverride All in your site configuration, or your schema will be browseable.."
HTACCESS="deny from all"
echo -e $HTACCESS > $SCHEMADIR/.htaccess

#Write config file
echo -e "Writing git_db_schema config file."
CONFIG="db = $DATABASE\nbranches = $BRANCHES"
echo -e $CONFIG > $SCHEMADIR/config

#Perform first dbschema dump
echo -e "Performing first db dump."
if [ $CREATEMC == "Y" ] ; 
then 
    mysqldump --defaults-group-suffix=_git_db_schema_$DATABASE --no-data $DATABASE > $SCHEMADIR/git_db_schema.sql
else
    mysqldump -u $MYSQLUSER --password="$MYSQLPASS" --no-data $DATABASE > $SCHEMADIR/git_db_schema.sql
fi

#verify dump
if ! grep --quiet 'Dump completed on' $SCHEMADIR/git_db_schema.sql ;
then
    echo -e 'There was a problem with dumping your database. Exiting.'
    exit
fi

#writing git hooks
if [ ! -e .git/hooks ] ;
then
    echo -e "The git/hooks directory does not exist, creating directory."
    mkdir .git/hooks
fi

#write post-commit hook
echo -e 'Writing post-commit hook'
cat > $GITDIR/.git/hooks/post-commit << 'EOF'
#!/bin/bash -e
GITDIR=$(git rev-parse --show-toplevel)
if [ -f $GITDIR/.git_db_schema/config ] ;
then
    DATABASE=$(sed -n -e 's/db = //p' .git_db_schema/config)
    BRANCHES=$(sed -n -e 's/branches = //p' .git_db_schema/config)
else
    echo -e "Cannot access git_db_schema config file, the db schema will not be updated."
    exit
fi
if [ $BRANCHES != "" ] ;
then
    #see if current 
    CURRENTBRANCH=$(git rev-parse --symbolic-full-name --abbrev-ref HEAD)
    if ! grep --quiet "$CURRENTBRANCH" <<< $BRANCHES ;
    then
        exit
    fi
fi
while [[ $UPDATE != "Y" && $UPDATE != "N" ]] ; do
    read -p "Do you wish to update your db schema (Y/N):" UPDATE
    if [[ $UPDATE != "Y" && $UPDATE != "N" ]] ;
    then
        echo -e 'This is not a valid entry'
    fi
done
if [ $UPDATE == "Y" ] ;
then
    if grep --quiet "client_git_db_schema_$DATABASE" ~/.my.cnf ;
    then
        mysqldump --defaults-group-suffix=_git_db_schema_$DATABASE --no-data $DATABASE > $GITDIR/.git_db_schema/git_db_schema.sql
    else
        #Get username and password for mysql
        read -p "Mysql username:" MYSQLUSER
        read -s -p "Mysql password:" MYSQLPASS
        ATTEMPTS=0
        echo -e "Testing MYSQL connection"
        while ! mysql -u $MYSQLUSER --password="$MYSQLPASS" $DATABASE  -e ";" > /dev/null ; do
            echo -e "Could not connect to MYSQL please try again"
            read -p "Mysql username:" MYSQLUSER
            read -s -p "Mysql password:" MYSQLPASS
            ATTEMPTS=$ATTEMPTS + 1
            if [ $ATTEMPTS >= 3 ] ;
            then
                echo -e "Three or more failed attempts, exiting"
                exit
            fi
        done
        mysqldump -u $MYSQLUSER --password="$MYSQLPASS" --no-data $DATABASE > $GITDIR/.git_db_schema/git_db_schema.sql
    fi
else
    exit
fi

if ! grep --quiet 'Dump completed on' $GITDIR/.git_db_schema/git_db_schema.sql ;
then
    echo -e 'There was a problem with dumping your database. Exiting.'
    exit
fi
git add $GITDIR/.git_db_schema/git_db_schema.sql
git commit -m 'git_db_schema updated'
EOF



#Writing post merge script
echo -e 'Writing post-merge hook.'
cat > $GITDIR/.git/hooks/post-merge << 'EOF'
#!/bin/bash -e
GITDIR=$(git rev-parse --show-toplevel)
if [ -f $GITDIR/.git_db_schema/config ] ;
then
    DATABASE=$(sed -n -e 's/db = //p' .git_db_schema/config)
    BRANCHES=$(sed -n -e 's/branches = //p' .git_db_schema/config)
else
    echo -e "Cannot access git_db_schema config file, the db schema will not be updated."
    exit
fi
if [ $BRANCHES != "" ] ;
then
    #see if current 
    CURRENTBRANCH=$(git rev-parse --symbolic-full-name --abbrev-ref HEAD)
    if ! grep --quiet "$CURRENTBRANCH" <<< $BRANCHES ;
    then
        exit
    fi
fi
while [[ $UPDATE != "Y" && $UPDATE != "N" ]] ; do
    read -p "Do you wish to check to see if your database needs updating from your database schema on file(Y/N):" UPDATE
    if [[ $UPDATE != "Y" && $UPDATE != "N" ]] ;
    then
        echo -e 'This is not a valid entry'
    fi
done
if [ $UPDATE == "Y" ] ;
then
    if grep --quiet "client_git_db_schema_$DATABASE" ~/.my.cnf ;
    then
        mysqldump --defaults-group-suffix=_git_db_schema_$DATABASE --no-data $DATABASE > $GITDIR/.git_db_schema/temp_schema.sql
    else
        #Get username and password for mysql
        read -p "Mysql username:" MYSQLUSER
        read -s -p "Mysql password:" MYSQLPASS
        ATTEMPTS=0
        echo -e "Testing MYSQL connection"
        while ! mysql -u $MYSQLUSER --password="$MYSQLPASS" $DATABASE  -e ";" > /dev/null ; do
            echo -e "Could not connect to MYSQL please try again"
            read -p "Mysql username:" MYSQLUSER
            read -s -p "Mysql password:" MYSQLPASS
            ATTEMPTS=$ATTEMPTS + 1
            if [ $ATTEMPTS >= 3 ] ;
            then
                echo -e "Three or more failed attempts, exiting"
                exit
            fi
        done
        mysqldump -u $MYSQLUSER --password="$MYSQLPASS" --no-data $DATABASE > $GITDIR/.git_db_schema/temp_schema.sql
    fi
else
    exit
fi
if ! grep --quiet 'Dump completed on' $GITDIR/.git_db_schema/temp_schema.sql ;
then
    echo -e 'There was a problem with dumping your database. Exiting.'
    exit
fi
SCHEMADIFF= $(mysql-schema-diff $GITDIR/.git_db_schema/git_db_schema.sql $GITDIR/.git_db_schema/temp_schema.sql)
echo -e "This is your schema differneces:"
echo $SCHEMADIFF
while [[ $UPDATEDB != "Y" && $UPDATEDB != "N" ]] ; do
    read -p "Do you want to implement these changes(Y/N):" UPDATEDB
    if [[ $UPDATEDB != "Y" && $UPDATEDB != "N" ]] ;
    then
        echo -e 'This is not a valid entry'
    fi
done
if [ $UPDATEDB == "Y" ] ;
then
    while [! -d $BACKUP ] ; do
        read -p "The database will be backed up first , please provide a path:(default is ~/)" BACKUP
        if [ $BACKUP == "" ] ;
        then
            $BACKUP = "~/"
        fi
        if [! -d $BACKUP] ;
        then
            echo -e 'This is not a valid directory'
        fi
    done
    DATE= $(date +%m_%d_%y-%k:%M:%S);
    if grep --quiet "client_git_db_schema_$DATABASE" ~/.my.cnf ;
    then
        mysqldump --defaults-group-suffix=_git_db_schema_$DATABASE  $DATABASE > $BACKUP/$DATABASE_$DATE.sql
        if ! grep --quiet 'Dump completed on' $BACKUP/$DATABASE_$DATE.sql ;
        then
            echo -e 'There was a problem with dumping your database. Exiting.'
            exit
        fi
        echo -e 'Database dumped, applying changes'
        mysql --defaults-group-suffix=_git_db_schema_$DATABASE --execute="$SCHEMADIFF"
    else
        mysqldump -u $MYSQLUSER --password="$MYSQLPASS" --no-data $DATABASE > $BACKUP/$DATABASE_$DATE.sql
        if ! grep --quiet 'Dump completed on' $BACKUP/$DATABASE_$DATE.sql ;
        then
            echo -e 'There was a problem with dumping your database. Exiting.'
            exit
        fi
        echo -e 'Database dumped, applying changes'
        mysql -u $MYSQLUSER --password="$MYSQLPASS" --execute="$SCHEMADIFF"
    fi
    echo -e "Saving db update"
    echo -e $SCHEMADIFF >> $GITDIR/.git_db_schema/db_update.$DATE.$HOSTNAME.sql
    git add $GITDIR/.git_db_schema/db_update.$DATE.$HOSTNAME.sql
    git commit -m "updated db on host $HOST on $DATE"
    echo -e "Database updated, a backup was saved at $BACKUP/$DATABASE_$DATE.sql"
else
    exit
fi
EOF

#git add
echo -e "Adding to git repository"
git add $SCHEMADIR/git_db_schema.sql
git add $SCHEMADIR/.htaccess
git add $SCHEMADIR/config

git commit -m "Initial db schema commit"


